package com.flower.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.flower.domain.entity.*;
import com.flower.domain.vo.farmer.FlowerEncyclopediaDetailVO;
import com.flower.domain.vo.farmer.FlowerEncyclopediaVO;
import com.flower.mapper.*;
import com.flower.service.FlowerEncyclopediaService;
import com.flower.utils.RedisUtils;
import com.flower.utils.UserContext;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.HashMap;

/**
 * 花卉百科服务实现类
 */
@Service
@Slf4j
public class FlowerEncyclopediaServiceImpl extends ServiceImpl<FlowerEncyclopediaMapper, FlowerEncyclopedia>
        implements FlowerEncyclopediaService {

    @Autowired
    private FlowerEncyclopediaMapper encyclopediaMapper;

    @Autowired
    private FlowerGrowingEnvironmentMapper growingEnvironmentMapper;

    @Autowired
    private FlowerGrowthStageMapper growthStageMapper;

    @Autowired
    private FlowerCultivationMethodMapper cultivationMethodMapper;

    @Autowired
    private FlowerImageMapper imageMapper;

    @Autowired
    private FlowerEditHistoryMapper flowerEditHistoryMapper;

    @Autowired
    private FlowerCultureMapper flowerCultureMapper;

    @Autowired
    private RedisUtils redisUtils;

    // Redis中存储待审核花卉信息的key前缀
    private static final String REDIS_ENCYCLOPEDIA_AUDIT_KEY_PREFIX = "flower:encyclopedia:audit:";

    // Redis中待审核数据的默认过期时间（7天）
    private static final long REDIS_AUDIT_EXPIRE_TIME = 7 * 24 * 60 * 60;

    @Override
    public Page<FlowerEncyclopediaVO> getEncyclopediaPage(Integer page, Integer pageSize, Map<String, Object> params) {
        // 构建查询条件
        LambdaQueryWrapper<FlowerEncyclopedia> wrapper = new LambdaQueryWrapper<>();

        // 添加查询条件
        String keyword = (String) params.get("keyword");
        if (StringUtils.isNotBlank(keyword)) {
            wrapper.and(qw -> qw.like(FlowerEncyclopedia::getName, keyword)
                    .or()
                    .like(FlowerEncyclopedia::getScientificName, keyword)
                    .or()
                    .like(FlowerEncyclopedia::getAlias, keyword));
        }

        String family = (String) params.get("family");
        if (StringUtils.isNotBlank(family)) {
            wrapper.eq(FlowerEncyclopedia::getFamily, family);
        }

        String genus = (String) params.get("genus");
        if (StringUtils.isNotBlank(genus)) {
            wrapper.eq(FlowerEncyclopedia::getGenus, genus);
        }

        Integer difficulty = (Integer) params.get("difficulty");
        if (difficulty != null) {
            wrapper.eq(FlowerEncyclopedia::getCultivationDifficulty, difficulty);
        }

        wrapper.eq(FlowerEncyclopedia::getStatus, 1); // 通过审核的

        // 按创建时间降序排序
        wrapper.orderByDesc(FlowerEncyclopedia::getViewCount);

        // 执行分页查询
        Page<FlowerEncyclopedia> pageParam = new Page<>(page, pageSize);
        Page<FlowerEncyclopedia> originPage = page(pageParam, wrapper);

        // 转换为VO
        Page<FlowerEncyclopediaVO> resultPage = new Page<>();
        BeanUtils.copyProperties(originPage, resultPage, "records");

        // 手动转换记录列表
        List<FlowerEncyclopediaVO> voList = originPage.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        resultPage.setRecords(voList);

        return resultPage;
    }

    @Override
    public Page<FlowerEncyclopediaVO> getEncyclopediaAuditsPage(Integer page, Integer pageSize, String keyword) {
        // 构建查询条件
        LambdaQueryWrapper<FlowerEncyclopedia> wrapper = new LambdaQueryWrapper<>();

        // 添加查询条件
        if (StringUtils.isNotBlank(keyword)) {
            wrapper.and(qw -> qw.like(FlowerEncyclopedia::getName, keyword)
                    .or()
                    .like(FlowerEncyclopedia::getScientificName, keyword)
                    .or()
                    .like(FlowerEncyclopedia::getAlias, keyword));
        }

        wrapper.eq(FlowerEncyclopedia::getStatus, 0); // 未通过审核的

        // 按创建时间降序排序
        wrapper.orderByDesc(FlowerEncyclopedia::getCreateTime);

        // 执行分页查询
        Page<FlowerEncyclopedia> pageParam = new Page<>(page, pageSize);
        Page<FlowerEncyclopedia> originPage = page(pageParam, wrapper);

        // 转换为VO
        Page<FlowerEncyclopediaVO> resultPage = new Page<>();
        BeanUtils.copyProperties(originPage, resultPage, "records");

        // 手动转换记录列表
        List<FlowerEncyclopediaVO> voList = originPage.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        resultPage.setRecords(voList);

        return resultPage;
    }

    @Override
    public FlowerEncyclopediaDetailVO getEncyclopediaDetail(Long id) {
        FlowerEncyclopedia entity = this.getById(id);
        if (entity == null) {
            return null;
        }
        return convertToDetailVO(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addEncyclopedia(FlowerEncyclopediaDetailVO detailVO, Long userId, Integer userType) {
        // 检查花卉名称是否已存在
        LambdaQueryWrapper<FlowerEncyclopedia> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FlowerEncyclopedia::getName, detailVO.getName());
        if (this.count(wrapper) > 0) {
            return false; // 花卉名称已存在
        }

        // 保存基本信息
        FlowerEncyclopedia encyclopedia = new FlowerEncyclopedia();
        BeanUtils.copyProperties(detailVO, encyclopedia);
        encyclopedia.setStatus(0); // 默认等待审核
        encyclopedia.setDataSource(1); // 花农上传
        encyclopedia.setCreatorId(userId);
        encyclopedia.setViewCount(0L);
        Long farmerId = UserContext.getUserId(); // 获取用户ID
        encyclopedia.setCreatorId(farmerId);
        boolean saved = this.save(encyclopedia);

        if (!saved) {
            return false;
        }

        Long encyclopediaId = encyclopedia.getId();

        // 保存生长环境
        if (detailVO.getGrowingEnvironment() != null) {
            FlowerGrowingEnvironment environment = new FlowerGrowingEnvironment();
            BeanUtils.copyProperties(detailVO.getGrowingEnvironment(), environment);
            environment.setEncyclopediaId(encyclopediaId);
            growingEnvironmentMapper.insert(environment);
        }

        // 保存生长阶段
        if (detailVO.getGrowthStages() != null && !detailVO.getGrowthStages().isEmpty()) {
            for (FlowerEncyclopediaDetailVO.FlowerGrowthStageVO stageVO : detailVO.getGrowthStages()) {
                FlowerGrowthStage stage = new FlowerGrowthStage();
                BeanUtils.copyProperties(stageVO, stage);
                stage.setEncyclopediaId(encyclopediaId);
                growthStageMapper.insert(stage);

                // 保存阶段图片
                if (stageVO.getImages() != null && !stageVO.getImages().isEmpty()) {
                    for (FlowerEncyclopediaDetailVO.FlowerImageVO imageVO : stageVO.getImages()) {
                        FlowerImage image = new FlowerImage();
                        BeanUtils.copyProperties(imageVO, image);
                        image.setEncyclopediaId(encyclopediaId);
                        image.setGrowthStageId(stage.getId());
                        imageMapper.insert(image);
                    }
                }
            }
        }

        // 保存栽培方法
        if (detailVO.getCultivationMethods() != null && !detailVO.getCultivationMethods().isEmpty()) {
            for (FlowerEncyclopediaDetailVO.FlowerCultivationMethodVO methodVO : detailVO.getCultivationMethods()) {
                FlowerCultivationMethod method = new FlowerCultivationMethod();
                BeanUtils.copyProperties(methodVO, method);
                method.setEncyclopediaId(encyclopediaId);
                cultivationMethodMapper.insert(method);
            }
        }

        // 保存图片
        if (detailVO.getImages() != null && !detailVO.getImages().isEmpty()) {
            for (FlowerEncyclopediaDetailVO.FlowerImageVO imageVO : detailVO.getImages()) {
                FlowerImage image = new FlowerImage();
                BeanUtils.copyProperties(imageVO, image);
                image.setEncyclopediaId(encyclopediaId);
                image.setGrowthStageId(null); // 确保不是阶段图片
                imageMapper.insert(image);
            }
        }

        // 保存文化信息
        if (detailVO.getCurltures() != null) {
            FlowerCulture curlture = new FlowerCulture();
            BeanUtils.copyProperties(detailVO.getCurltures(), curlture);
            curlture.setEncyclopediaId(encyclopediaId);
            flowerCultureMapper.insert(curlture);
        }

        // 记录编辑历史
        FlowerEditHistory history = new FlowerEditHistory();
        history.setEncyclopediaId(encyclopediaId);
        history.setEditorId(userId);
        history.setEditorType(userType);
        history.setEditContent("创建花卉百科");
        history.setEditTime(LocalDateTime.now());
        history.setIpAddress("127.0.0.1"); // TODO: 获取真实IP
        flowerEditHistoryMapper.insert(history);

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateEncyclopedia(Long id, FlowerEncyclopediaDetailVO detailVO, Long userId, Integer userType) {
        log.info("更新花卉百科，id={}, detailVO={}", id, detailVO);
        // 检查是否存在
        FlowerEncyclopedia encyclopedia = this.getById(id);
        if (encyclopedia == null) {
            return false;
        }

        // 检查名称是否重复
        if (!encyclopedia.getName().equals(detailVO.getName())) {
            LambdaQueryWrapper<FlowerEncyclopedia> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(FlowerEncyclopedia::getName, detailVO.getName());
            wrapper.ne(FlowerEncyclopedia::getId, id);
            if (this.count(wrapper) > 0) {
                return false; // 花卉名称已存在
            }
        }
        // 更新基本信息
        encyclopedia.setId(id); // 确保ID不变
        encyclopedia.setStatus(0); // 更新后需要重新审核
        encyclopedia.setUpdateTime(LocalDateTime.now());
        boolean updated = this.updateById(encyclopedia);
        if (!updated) {
            return false;
        }

        // 将更新的数据存入Redis，等待审核
        String redisKey = REDIS_ENCYCLOPEDIA_AUDIT_KEY_PREFIX + id;

        // 将整个detailVO对象转为JSON存储
        boolean result = redisUtils.set(redisKey, JSON.toJSONString(detailVO), REDIS_AUDIT_EXPIRE_TIME);

        if (result) {
            // 记录编辑历史
            FlowerEditHistory history = new FlowerEditHistory();
            history.setEncyclopediaId(id);
            history.setEditorId(userId);
            history.setEditorType(userType);
            history.setEditContent("修改花卉百科信息，等待审核");
            history.setEditTime(LocalDateTime.now());
            history.setIpAddress("127.0.0.1"); // TODO: 获取真实IP
            flowerEditHistoryMapper.insert(history);

            log.info("花卉百科[{}]更新已提交审核", id);
        } else {
            log.error("花卉百科[{}]更新提交失败", id);
        }

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteEncyclopedia(Long id) {
        // 检查是否存在
        if (!this.getBaseMapper()
                .exists(new LambdaQueryWrapper<FlowerEncyclopedia>().eq(FlowerEncyclopedia::getId, id))) {
            return false;
        }

        // 删除生长环境
        LambdaQueryWrapper<FlowerGrowingEnvironment> envWrapper = new LambdaQueryWrapper<>();
        envWrapper.eq(FlowerGrowingEnvironment::getEncyclopediaId, id);
        growingEnvironmentMapper.delete(envWrapper);

        // 删除生长阶段相关图片
        LambdaQueryWrapper<FlowerGrowthStage> stageWrapper = new LambdaQueryWrapper<>();
        stageWrapper.eq(FlowerGrowthStage::getEncyclopediaId, id);
        List<FlowerGrowthStage> stages = growthStageMapper.selectList(stageWrapper);
        for (FlowerGrowthStage stage : stages) {
            LambdaQueryWrapper<FlowerImage> stageImageWrapper = new LambdaQueryWrapper<>();
            stageImageWrapper.eq(FlowerImage::getGrowthStageId, stage.getId());
            imageMapper.delete(stageImageWrapper);
        }

        // 删除生长阶段
        growthStageMapper.delete(stageWrapper);

        // 删除栽培方法
        LambdaQueryWrapper<FlowerCultivationMethod> methodWrapper = new LambdaQueryWrapper<>();
        methodWrapper.eq(FlowerCultivationMethod::getEncyclopediaId, id);
        cultivationMethodMapper.delete(methodWrapper);

        // 删除图片
        LambdaQueryWrapper<FlowerImage> imageWrapper = new LambdaQueryWrapper<>();
        imageWrapper.eq(FlowerImage::getEncyclopediaId, id);
        imageMapper.delete(imageWrapper);

        // 删除编辑历史
        LambdaQueryWrapper<FlowerEditHistory> historyWrapper = new LambdaQueryWrapper<>();
        historyWrapper.eq(FlowerEditHistory::getEncyclopediaId, id);
        flowerEditHistoryMapper.delete(historyWrapper);

        // 删除文化信息
        LambdaQueryWrapper<FlowerCulture> cultureWrapper = new LambdaQueryWrapper<>();
        cultureWrapper.eq(FlowerCulture::getEncyclopediaId, id);
        flowerCultureMapper.delete(cultureWrapper);

        // 删除基本信息
        return this.removeById(id);
    }

    @Override
    public void incrementViewCount(Long id) {
        FlowerEncyclopedia encyclopedia = this.getById(id);
        if (encyclopedia != null) {
            encyclopedia.setViewCount(encyclopedia.getViewCount() + 1);
            this.updateById(encyclopedia);
        }
    }

    @Override
    public List<FlowerEncyclopediaVO> getHotEncyclopedias(Integer limit) {
        LambdaQueryWrapper<FlowerEncyclopedia> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FlowerEncyclopedia::getStatus, 1); // 只查询已发布的
        wrapper.orderByDesc(FlowerEncyclopedia::getViewCount);
        wrapper.last("LIMIT " + limit);

        List<FlowerEncyclopedia> hotList = this.list(wrapper);

        return hotList.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean crawlFlowerData(String url) {
        try {
            if (StringUtils.isBlank(url)) {
                log.error("爬取URL不能为空");
                return false;
            }

            // 判断URL类型并选择相应的爬虫方法
            Document doc = Jsoup.connect(url).get();

            // 示例：从花卉网爬取数据
            if (url.contains("huahuahua.com")) {
                return crawlFromHuahua(doc);
            }
            // 示例：从花卉百科网爬取数据
            else if (url.contains("huabaike.com")) {
                return crawlFromBaike(doc);
            }
            // 示例：从其他网站爬取数据
            else {
                return crawlFromGeneral(doc);
            }
        } catch (IOException e) {
            log.error("爬取花卉数据失败: {}", e.getMessage(), e);
            return false;
        } catch (Exception e) {
            log.error("处理花卉数据失败: {}", e.getMessage(), e);
            return false;
        }
    }

    /**
     * 从花卉网爬取数据
     */
    private boolean crawlFromHuahua(Document doc) {
        try {
            // 提取花卉基本信息
            String name = doc.select("h1.flower-name").text();
            if (StringUtils.isBlank(name)) {
                log.error("无法获取花卉名称");
                return false;
            }

            // 检查是否已存在
            LambdaQueryWrapper<FlowerEncyclopedia> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(FlowerEncyclopedia::getName, name);
            if (this.count(wrapper) > 0) {
                log.error("花卉已存在: {}", name);
                return false;
            }

            // 创建百科详情对象
            FlowerEncyclopediaDetailVO detailVO = new FlowerEncyclopediaDetailVO();
            detailVO.setName(name);
            detailVO.setScientificName(doc.select("div.scientific-name").text());
            detailVO.setAlias(doc.select("div.alias").text());
            detailVO.setFamily(doc.select("div.family").text());
            detailVO.setGenus(doc.select("div.genus").text());
            detailVO.setOrigin(doc.select("div.origin").text());
            detailVO.setIntroduction(doc.select("div.introduction").text());
            detailVO.setFeatures(doc.select("div.features").text());

            // 设置养护难度
            String difficultyStr = doc.select("div.difficulty").text();
            try {
                detailVO.setCultivationDifficulty(Integer.parseInt(difficultyStr));
            } catch (NumberFormatException e) {
                detailVO.setCultivationDifficulty(3); // 默认中等难度
            }

            // 设置缩略图
            Element thumbnailElement = doc.select("img.flower-thumbnail").first();
            if (thumbnailElement != null) {
                detailVO.setThumbnail(thumbnailElement.attr("src"));
            }

            // 设置生长环境
            FlowerEncyclopediaDetailVO.FlowerGrowingEnvironmentVO environmentVO = new FlowerEncyclopediaDetailVO.FlowerGrowingEnvironmentVO();
            environmentVO.setLightRequirement(doc.select("div.light-requirement").text());
            environmentVO.setWaterRequirement(doc.select("div.water-requirement").text());
            environmentVO.setSoilType(doc.select("div.soil-type").text());
            environmentVO.setHumidity(doc.select("div.humidity").text());
            environmentVO.setFertilization(doc.select("div.fertilization").text());
            detailVO.setGrowingEnvironment(environmentVO);

            // 提取生长阶段信息
            Elements stageElements = doc.select("div.growth-stage");
            if (!stageElements.isEmpty()) {
                List<FlowerEncyclopediaDetailVO.FlowerGrowthStageVO> growthStages = new ArrayList<>();
                int sortOrder = 1;

                for (Element stageElement : stageElements) {
                    FlowerEncyclopediaDetailVO.FlowerGrowthStageVO stageVO = new FlowerEncyclopediaDetailVO.FlowerGrowthStageVO();
                    stageVO.setStageName(stageElement.select("h3.stage-name").text());
                    stageVO.setStageDescription(stageElement.select("div.stage-description").text());
                    stageVO.setDuration(stageElement.select("div.duration").text());
                    stageVO.setCareTips(stageElement.select("div.care-tips").text());
                    stageVO.setSortOrder(sortOrder++);

                    // 提取阶段图片
                    Elements imageElements = stageElement.select("img.stage-image");
                    if (!imageElements.isEmpty()) {
                        List<FlowerEncyclopediaDetailVO.FlowerImageVO> stageImages = new ArrayList<>();
                        for (Element imageElement : imageElements) {
                            FlowerEncyclopediaDetailVO.FlowerImageVO imageVO = new FlowerEncyclopediaDetailVO.FlowerImageVO();
                            imageVO.setImageUrl(imageElement.attr("src"));
                            imageVO.setDescription(imageElement.attr("alt"));
                            stageImages.add(imageVO);
                        }
                        stageVO.setImages(stageImages);
                    }

                    growthStages.add(stageVO);
                }

                detailVO.setGrowthStages(growthStages);
            }

            // 提取栽培方法
            Elements methodElements = doc.select("div.cultivation-method");
            if (!methodElements.isEmpty()) {
                List<FlowerEncyclopediaDetailVO.FlowerCultivationMethodVO> cultivationMethods = new ArrayList<>();
                int sortOrder = 1;

                for (Element methodElement : methodElements) {
                    FlowerEncyclopediaDetailVO.FlowerCultivationMethodVO methodVO = new FlowerEncyclopediaDetailVO.FlowerCultivationMethodVO();
                    methodVO.setMethodName(methodElement.select("h3.method-name").text());
                    methodVO.setMethodContent(methodElement.select("div.method-content").text());
                    methodVO.setSuitableSeason(methodElement.select("div.suitable-season").text());
                    methodVO.setSortOrder(sortOrder++);
                    cultivationMethods.add(methodVO);
                }

                detailVO.setCultivationMethods(cultivationMethods);
            }

            // 提取花卉图片
            Elements galleryElements = doc.select("div.flower-gallery img");
            if (!galleryElements.isEmpty()) {
                List<FlowerEncyclopediaDetailVO.FlowerImageVO> images = new ArrayList<>();
                int sortOrder = 1;

                for (Element imgElement : galleryElements) {
                    FlowerEncyclopediaDetailVO.FlowerImageVO imageVO = new FlowerEncyclopediaDetailVO.FlowerImageVO();
                    imageVO.setImageUrl(imgElement.attr("src"));
                    imageVO.setDescription(imgElement.attr("alt"));
                    imageVO.setImageType(1); // 默认全株
                    imageVO.setIsMain(sortOrder == 1 ? 1 : 0); // 第一张为主图
                    imageVO.setSortOrder(sortOrder++);
                    images.add(imageVO);
                }

                detailVO.setImages(images);
            }

            // 保存爬取的数据
            return addEncyclopedia(detailVO, 0L, 3); // 系统爬虫

        } catch (Exception e) {
            log.error("解析花卉网数据失败: {}", e.getMessage(), e);
            return false;
        }
    }

    /**
     * 从花卉百科网爬取数据
     */
    private boolean crawlFromBaike(Document doc) {
        // 实现类似上面的爬虫逻辑，根据目标网站结构进行调整
        return false;
    }

    /**
     * 从通用网站爬取数据
     */
    private boolean crawlFromGeneral(Document doc) {
        // 实现通用爬虫逻辑
        return false;
    }

    /**
     * 将实体转换为VO
     */
    private FlowerEncyclopediaVO convertToVO(FlowerEncyclopedia encyclopedia) {
        if (encyclopedia == null) {
            return null;
        }

        FlowerEncyclopediaVO vo = new FlowerEncyclopediaVO();
        BeanUtils.copyProperties(encyclopedia, vo);

        // 设置创建者名称
        if (encyclopedia.getDataSource() == 1) {
            // TODO: 查询用户信息设置创建者名称
            vo.setCreatorName("花农用户");
            vo.setCreatorType(1); // 花农
        } else if (encyclopedia.getDataSource() == 2) {
            vo.setCreatorName("系统采集");
            vo.setCreatorType(3); // 系统
        } else {
            vo.setCreatorName("管理员");
            vo.setCreatorType(2); // 管理员
        }

        // 初始化待审核更新状态为false，在控制器中再更新
        vo.setHasPendingUpdate(false);

        return vo;
    }

    /**
     * 将实体转换为DetailVO
     */
    private FlowerEncyclopediaDetailVO convertToDetailVO(FlowerEncyclopedia entity) {
        if (entity == null) {
            return null;
        }

        FlowerEncyclopediaDetailVO vo = new FlowerEncyclopediaDetailVO();
        BeanUtils.copyProperties(entity, vo);

        // 转换生长环境
        LambdaQueryWrapper<FlowerGrowingEnvironment> envWrapper = new LambdaQueryWrapper<>();
        envWrapper.eq(FlowerGrowingEnvironment::getEncyclopediaId, entity.getId());
        FlowerGrowingEnvironment environment = growingEnvironmentMapper.selectOne(envWrapper);
        if (environment != null) {
            FlowerEncyclopediaDetailVO.FlowerGrowingEnvironmentVO envVO = new FlowerEncyclopediaDetailVO.FlowerGrowingEnvironmentVO();
            BeanUtils.copyProperties(environment, envVO);
            vo.setGrowingEnvironment(envVO);
        }

        // 转换生长阶段
        LambdaQueryWrapper<FlowerGrowthStage> stageWrapper = new LambdaQueryWrapper<>();
        stageWrapper.eq(FlowerGrowthStage::getEncyclopediaId, entity.getId());
        stageWrapper.orderByAsc(FlowerGrowthStage::getSortOrder);
        List<FlowerGrowthStage> stages = growthStageMapper.selectList(stageWrapper);

        if (!stages.isEmpty()) {
            List<FlowerEncyclopediaDetailVO.FlowerGrowthStageVO> stageVOs = new ArrayList<>();
            for (FlowerGrowthStage stage : stages) {
                FlowerEncyclopediaDetailVO.FlowerGrowthStageVO stageVO = new FlowerEncyclopediaDetailVO.FlowerGrowthStageVO();
                BeanUtils.copyProperties(stage, stageVO);

                // 转换阶段图片
                LambdaQueryWrapper<FlowerImage> stageImageWrapper = new LambdaQueryWrapper<>();
                stageImageWrapper.eq(FlowerImage::getGrowthStageId, stage.getId());
                stageImageWrapper.orderByAsc(FlowerImage::getSortOrder);
                List<FlowerImage> stageImages = imageMapper.selectList(stageImageWrapper);

                if (!stageImages.isEmpty()) {
                    List<FlowerEncyclopediaDetailVO.FlowerImageVO> imageVOs = new ArrayList<>();
                    for (FlowerImage image : stageImages) {
                        FlowerEncyclopediaDetailVO.FlowerImageVO imageVO = new FlowerEncyclopediaDetailVO.FlowerImageVO();
                        BeanUtils.copyProperties(image, imageVO);
                        imageVOs.add(imageVO);
                    }
                    stageVO.setImages(imageVOs);
                }

                stageVOs.add(stageVO);
            }
            vo.setGrowthStages(stageVOs);
        }

        // 转换栽培方法
        LambdaQueryWrapper<FlowerCultivationMethod> methodWrapper = new LambdaQueryWrapper<>();
        methodWrapper.eq(FlowerCultivationMethod::getEncyclopediaId, entity.getId());
        methodWrapper.orderByAsc(FlowerCultivationMethod::getSortOrder);
        List<FlowerCultivationMethod> methods = cultivationMethodMapper.selectList(methodWrapper);

        if (!methods.isEmpty()) {
            List<FlowerEncyclopediaDetailVO.FlowerCultivationMethodVO> methodVOs = new ArrayList<>();
            for (FlowerCultivationMethod method : methods) {
                FlowerEncyclopediaDetailVO.FlowerCultivationMethodVO methodVO = new FlowerEncyclopediaDetailVO.FlowerCultivationMethodVO();
                BeanUtils.copyProperties(method, methodVO);
                methodVOs.add(methodVO);
            }
            vo.setCultivationMethods(methodVOs);
        }

        // 转换图片
        LambdaQueryWrapper<FlowerImage> imageWrapper = new LambdaQueryWrapper<>();
        imageWrapper.eq(FlowerImage::getEncyclopediaId, entity.getId());
        imageWrapper.isNull(FlowerImage::getGrowthStageId);
        imageWrapper.orderByAsc(FlowerImage::getSortOrder);
        List<FlowerImage> images = imageMapper.selectList(imageWrapper);

        if (!images.isEmpty()) {
            List<FlowerEncyclopediaDetailVO.FlowerImageVO> imageVOs = new ArrayList<>();
            for (FlowerImage image : images) {
                FlowerEncyclopediaDetailVO.FlowerImageVO imageVO = new FlowerEncyclopediaDetailVO.FlowerImageVO();
                BeanUtils.copyProperties(image, imageVO);
                imageVOs.add(imageVO);
            }
            vo.setImages(imageVOs);
        }

        // 转换文化信息
        LambdaQueryWrapper<FlowerCulture> cultureWrapper = new LambdaQueryWrapper<>();
        cultureWrapper.eq(FlowerCulture::getEncyclopediaId, entity.getId());
        FlowerCulture culture = flowerCultureMapper.selectOne(cultureWrapper);
        if (culture != null) {
            FlowerEncyclopediaDetailVO.FlowerCurltureVO cultureVO = new FlowerEncyclopediaDetailVO.FlowerCurltureVO();
            BeanUtils.copyProperties(culture, cultureVO);
            vo.setCurltures(cultureVO);
        }
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateEncyclopediaStatus(Long id, Integer status) {
        // 只有当状态为1（审核通过）时才处理
        if (status == 1) {
            return approveEncyclopedia(id);
        } else if (status == 0) {
            // 状态为0，已经是待审核状态，无需处理
            return true;
        }
        return false;
    }

    /**
     * 审核通过花卉百科
     * 
     * @param id 百科ID
     * @return 审核结果
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean approveEncyclopedia(Long id) {
        // 检查Redis中是否有待审核的数据
        String redisKey = REDIS_ENCYCLOPEDIA_AUDIT_KEY_PREFIX + id;
        if (!redisUtils.hasKey(redisKey)) {
            log.warn("没有找到待审核的花卉百科数据[{}]", id);
            return false;
        }

        try {
            // 从Redis获取待审核数据
            String jsonData = (String) redisUtils.get(redisKey);
            FlowerEncyclopediaDetailVO detailVO = JSON.parseObject(jsonData, FlowerEncyclopediaDetailVO.class);

            if (detailVO == null) {
                log.error("解析Redis中的花卉百科数据失败[{}]", id);
                return false;
            }

            // 检查花卉是否存在
            FlowerEncyclopedia encyclopedia = this.getById(id);
            if (encyclopedia == null) {
                log.error("花卉百科不存在[{}]", id);
                return false;
            }

            // 更新基本信息
            BeanUtils.copyProperties(detailVO, encyclopedia);
            encyclopedia.setStatus(1); // 设置为已发布
            encyclopedia.setUpdateTime(LocalDateTime.now());
            this.updateById(encyclopedia);

            // 更新生长环境
            if (detailVO.getGrowingEnvironment() != null) {
                // 先删除原有的生长环境
                LambdaQueryWrapper<FlowerGrowingEnvironment> envWrapper = new LambdaQueryWrapper<>();
                envWrapper.eq(FlowerGrowingEnvironment::getEncyclopediaId, id);
                growingEnvironmentMapper.delete(envWrapper);

                // 添加新的生长环境
                FlowerGrowingEnvironment environment = new FlowerGrowingEnvironment();
                BeanUtils.copyProperties(detailVO.getGrowingEnvironment(), environment);
                environment.setEncyclopediaId(id);
                growingEnvironmentMapper.insert(environment);
            }

            // 更新生长阶段
            if (detailVO.getGrowthStages() != null && !detailVO.getGrowthStages().isEmpty()) {
                // 先删除原有的生长阶段
                LambdaQueryWrapper<FlowerGrowthStage> stageWrapper = new LambdaQueryWrapper<>();
                stageWrapper.eq(FlowerGrowthStage::getEncyclopediaId, id);
                List<FlowerGrowthStage> oldStages = growthStageMapper.selectList(stageWrapper);

                // 收集旧阶段的ID，用于删除关联的图片
                List<Long> oldStageIds = oldStages.stream()
                        .map(FlowerGrowthStage::getId)
                        .collect(Collectors.toList());

                // 删除旧阶段
                growthStageMapper.delete(stageWrapper);

                // 删除旧阶段关联的图片
                if (!oldStageIds.isEmpty()) {
                    LambdaQueryWrapper<FlowerImage> stageImageWrapper = new LambdaQueryWrapper<>();
                    stageImageWrapper.in(FlowerImage::getGrowthStageId, oldStageIds);
                    imageMapper.delete(stageImageWrapper);
                }

                // 添加新的生长阶段
                for (FlowerEncyclopediaDetailVO.FlowerGrowthStageVO stageVO : detailVO.getGrowthStages()) {
                    FlowerGrowthStage stage = new FlowerGrowthStage();
                    BeanUtils.copyProperties(stageVO, stage);
                    stage.setEncyclopediaId(id);
                    growthStageMapper.insert(stage);

                    // 添加阶段图片
                    if (stageVO.getImages() != null && !stageVO.getImages().isEmpty()) {
                        for (FlowerEncyclopediaDetailVO.FlowerImageVO imageVO : stageVO.getImages()) {
                            FlowerImage image = new FlowerImage();
                            BeanUtils.copyProperties(imageVO, image);
                            image.setEncyclopediaId(id);
                            image.setGrowthStageId(stage.getId());
                            imageMapper.insert(image);
                        }
                    }
                }
            }

            // 更新栽培方法
            if (detailVO.getCultivationMethods() != null && !detailVO.getCultivationMethods().isEmpty()) {
                // 先删除原有的栽培方法
                LambdaQueryWrapper<FlowerCultivationMethod> methodWrapper = new LambdaQueryWrapper<>();
                methodWrapper.eq(FlowerCultivationMethod::getEncyclopediaId, id);
                cultivationMethodMapper.delete(methodWrapper);

                // 添加新的栽培方法
                for (FlowerEncyclopediaDetailVO.FlowerCultivationMethodVO methodVO : detailVO.getCultivationMethods()) {
                    FlowerCultivationMethod method = new FlowerCultivationMethod();
                    BeanUtils.copyProperties(methodVO, method);
                    method.setEncyclopediaId(id);
                    cultivationMethodMapper.insert(method);
                }
            }

            // 更新图片
            if (detailVO.getImages() != null && !detailVO.getImages().isEmpty()) {
                // 先删除原有的非阶段图片
                LambdaQueryWrapper<FlowerImage> imageWrapper = new LambdaQueryWrapper<>();
                imageWrapper.eq(FlowerImage::getEncyclopediaId, id)
                        .isNull(FlowerImage::getGrowthStageId);
                imageMapper.delete(imageWrapper);

                // 添加新的图片
                for (FlowerEncyclopediaDetailVO.FlowerImageVO imageVO : detailVO.getImages()) {
                    FlowerImage image = new FlowerImage();
                    BeanUtils.copyProperties(imageVO, image);
                    image.setEncyclopediaId(id);
                    image.setGrowthStageId(null);
                    imageMapper.insert(image);
                }
            }

            // 更新花卉文化
            if (detailVO.getCurltures() != null) {
                // 先删除原有的花卉文化
                LambdaQueryWrapper<FlowerCulture> cultureWrapper = new LambdaQueryWrapper<>();
                cultureWrapper.eq(FlowerCulture::getEncyclopediaId, id);
                flowerCultureMapper.delete(cultureWrapper);

                // 添加新的花卉文化
                FlowerCulture culture = new FlowerCulture();
                BeanUtils.copyProperties(detailVO.getCurltures(), culture);
                culture.setEncyclopediaId(id);
                culture.setUpdateTime(LocalDateTime.now());
                flowerCultureMapper.insert(culture);
            }

            // 删除Redis中的数据
            redisUtils.delete(redisKey);

            // 更新基本信息
            encyclopedia.setId(id); // 确保ID不变
            encyclopedia.setStatus(1); // 通过审核
            encyclopedia.setUpdateTime(LocalDateTime.now());
            boolean updated = this.updateById(encyclopedia);
            if (!updated) {
                return false;
            }

            // 记录审核历史
            FlowerEditHistory history = new FlowerEditHistory();
            history.setEncyclopediaId(id);
            history.setEditorId(UserContext.getUserId());
            history.setEditorType(2); // 管理员
            history.setEditContent("审核通过花卉百科更新");
            history.setEditTime(LocalDateTime.now());
            history.setIpAddress("127.0.0.1"); // TODO: 获取真实IP
            flowerEditHistoryMapper.insert(history);

            log.info("花卉百科[{}]审核通过，更新成功", id);
            return true;

        } catch (Exception e) {
            log.error("花卉百科审核通过处理失败[{}]", id, e);
            return false;
        }
    }

    @Override
    public boolean rejectEncyclopedia(Long id, String reason) {
        // 检查Redis中是否有待审核的数据
        String redisKey = REDIS_ENCYCLOPEDIA_AUDIT_KEY_PREFIX + id;
        if (!redisUtils.hasKey(redisKey)) {
            log.warn("没有找到待审核的花卉百科数据[{}]", id);
            return false;
        }

        try {
            // 删除Redis中的数据
            redisUtils.delete(redisKey);
            FlowerEncyclopedia encyclopedia = this.getById(id);
            // 更新基本信息
            encyclopedia.setId(id); // 确保ID不变
            encyclopedia.setStatus(1); // 审核过了
            encyclopedia.setUpdateTime(LocalDateTime.now());
            boolean updated = this.updateById(encyclopedia);
            if (!updated) {
                return false;
            }

            // 记录拒绝历史
            FlowerEditHistory history = new FlowerEditHistory();
            history.setEncyclopediaId(id);
            history.setEditorId(UserContext.getUserId());
            history.setEditorType(2); // 管理员
            history.setEditContent("拒绝花卉百科更新：" + reason);
            history.setEditTime(LocalDateTime.now());
            history.setIpAddress("127.0.0.1"); // TODO: 获取真实IP
            flowerEditHistoryMapper.insert(history);

            log.info("花卉百科[{}]审核拒绝：{}", id, reason);
            return true;

        } catch (Exception e) {
            log.error("花卉百科审核拒绝处理失败[{}]", id, e);
            return false;
        }
    }

    @Override
    public FlowerEncyclopediaDetailVO getPendingEncyclopediaFromRedis(Long id) {
        String redisKey = REDIS_ENCYCLOPEDIA_AUDIT_KEY_PREFIX + id;
        if (!redisUtils.hasKey(redisKey)) {
            return null;
        }

        try {
            String jsonData = (String) redisUtils.get(redisKey);
            return JSON.parseObject(jsonData, FlowerEncyclopediaDetailVO.class);
        } catch (Exception e) {
            log.error("获取Redis中的花卉百科数据失败[{}]", id, e);
            return null;
        }
    }

    @Override
    public boolean hasPendingUpdate(Long id) {
        String redisKey = REDIS_ENCYCLOPEDIA_AUDIT_KEY_PREFIX + id;
        return redisUtils.hasKey(redisKey);
    }

    @Override
    public boolean existsByName(String name) {
        if (StringUtils.isBlank(name)) {
            return false;
        }
        return this.lambdaQuery()
                .eq(FlowerEncyclopedia::getName, name)
                .exists();
    }

    /**
     * 从Excel导入花卉百科数据
     *
     * @param data 从Excel转换的Map数据
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveEncyclopediaFromExcel(Map<String, Object> data) {
        try {
            // 创建花卉百科实体对象
            FlowerEncyclopedia encyclopedia = new FlowerEncyclopedia();

            // 设置基础信息
            encyclopedia.setName((String) data.get("name"));
            encyclopedia.setScientificName((String) data.get("scientificName"));
            encyclopedia.setFamily((String) data.get("family"));
            encyclopedia.setGenus((String) data.get("genus"));
            encyclopedia.setAlias((String) data.get("alias"));
            encyclopedia.setOrigin((String) data.get("origin"));
            encyclopedia.setRightPlace((String) data.get("rightPlace"));
            encyclopedia.setCultivationDifficulty((Integer) data.get("cultivationDifficulty"));
            encyclopedia.setIntroduction((String) data.get("introduction"));
            encyclopedia.setFeatures((String) data.get("features"));

            // 设置状态为待审核
            encyclopedia.setStatus(0);

            // 先保存百科基本信息，获取ID
            int result = encyclopediaMapper.insert(encyclopedia);
            if (result <= 0) {
                return false;
            }

            // 处理生长环境信息
            if (data.containsKey("growingEnvironment") && data.get("growingEnvironment") instanceof Map) {
                Map<String, Object> envMap = (Map<String, Object>) data.get("growingEnvironment");

                FlowerGrowingEnvironment environment = new FlowerGrowingEnvironment();
                environment.setEncyclopediaId(encyclopedia.getId());

                if (envMap.containsKey("temperatureMin")) {
                    environment.setTemperatureMin((BigDecimal) envMap.get("temperatureMin"));
                }

                if (envMap.containsKey("temperatureMax")) {
                    environment.setTemperatureMax((BigDecimal) envMap.get("temperatureMax"));
                }

                environment.setLightRequirement((String) envMap.get("lightRequirement"));
                environment.setWaterRequirement((String) envMap.get("waterRequirement"));
                environment.setSoilType((String) envMap.get("soilType"));
                environment.setHumidity((String) envMap.get("humidity"));
                environment.setFertilization((String) envMap.get("fertilization"));

                growingEnvironmentMapper.insert(environment);
            }

            log.info("成功从Excel导入花卉百科数据: {}", encyclopedia.getName());
            return true;
        } catch (Exception e) {
            log.error("保存Excel导入的花卉百科数据失败", e);
            throw new RuntimeException("保存Excel导入的花卉百科数据失败: " + e.getMessage());
        }
    }

    @Override
    public Map<String, Object> getEncyclopediaOverview() {
        Map<String, Object> result = new HashMap<>();
        
        // 总数量
        long total = count();
        result.put("total", total);
        
        // 待审核数量
        long pendingCount = count(new LambdaQueryWrapper<FlowerEncyclopedia>()
                .eq(FlowerEncyclopedia::getStatus, 0));
        result.put("pendingCount", pendingCount);
        
        // 今日新增
        LocalDateTime today = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
        long todayCount = count(new LambdaQueryWrapper<FlowerEncyclopedia>()
                .ge(FlowerEncyclopedia::getCreateTime, today));
        result.put("todayCount", todayCount);
        
        // 总浏览量
        Long totalViews = baseMapper.getTotalViewCount();
        result.put("totalViews", totalViews);
        
        // 数据来源分布
        result.put("sourceDistribution", getDataSourceDistribution());
        
        return result;
    }
    
    private Map<String, Object> getDataSourceDistribution() {
        Map<String, Object> result = new HashMap<>();
        
        // 0:系统采集, 1:花农上传, 2:管理员添加
        long crawlerCount = count(new LambdaQueryWrapper<FlowerEncyclopedia>()
                .eq(FlowerEncyclopedia::getDataSource, 0));
        long farmerCount = count(new LambdaQueryWrapper<FlowerEncyclopedia>()
                .eq(FlowerEncyclopedia::getDataSource, 1));
        long adminCount = count(new LambdaQueryWrapper<FlowerEncyclopedia>()
                .eq(FlowerEncyclopedia::getDataSource, 2));
                
        List<Map<String, Object>> list = new ArrayList<>();
        if (crawlerCount > 0) {
            list.add(Map.of("name", "系统采集", "value", crawlerCount));
        }
        if (farmerCount > 0) {
            list.add(Map.of("name", "花农上传", "value", farmerCount));
        }
        if (adminCount > 0) {
            list.add(Map.of("name", "管理员添加", "value", adminCount));
        }
        
        result.put("data", list);
        
        return result;
    }

    @Override
    public List<FlowerEncyclopediaVO> getTopViewsEncyclopedias(Integer limit) {
        LambdaQueryWrapper<FlowerEncyclopedia> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FlowerEncyclopedia::getStatus, 1); // 只查询已审核通过的
        wrapper.orderByDesc(FlowerEncyclopedia::getViewCount);
        wrapper.last("LIMIT " + limit);
        
        List<FlowerEncyclopedia> list = list(wrapper);
        return list.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public Map<String, Object> getEncyclopediaViewTrend(LocalDate startDate, LocalDate endDate, String timeUnit) {
        // 如果未指定日期范围，默认查询最近30天
        if (startDate == null) {
            startDate = LocalDate.now().minusDays(29);
        }
        if (endDate == null) {
            endDate = LocalDate.now();
        }
        
        // 根据不同时间单位聚合数据
        List<Map<String, Object>> viewTrend = baseMapper.getViewTrendByTimeUnit(
                startDate.atStartOfDay(), 
                endDate.plusDays(1).atStartOfDay(), 
                timeUnit);
        
        // 生成完整的日期列表（包含没有数据的日期）
        List<String> dateList = new ArrayList<>();
        List<Long> valueList = new ArrayList<>();
        
        Map<String, Long> dataMap = viewTrend.stream()
                .collect(Collectors.toMap(
                        item -> item.get("date").toString(),
                        item -> Long.valueOf(item.get("count").toString())
                ));
        
        // 根据不同时间单位生成日期列表
        LocalDate current = startDate;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(getDateFormatByTimeUnit(timeUnit));
        
        while (!current.isAfter(endDate)) {
            String dateKey = current.format(formatter);
            dateList.add(dateKey);
            valueList.add(dataMap.getOrDefault(dateKey, 0L));
            
            // 根据时间单位增加时间
            current = incrementDateByTimeUnit(current, timeUnit);
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("dates", dateList);
        result.put("values", valueList);
        
        return result;
    }
    
    private String getDateFormatByTimeUnit(String timeUnit) {
        return switch (timeUnit) {
            case "week" -> "yyyy-'W'ww";
            case "month" -> "yyyy-MM";
            default -> "yyyy-MM-dd";
        };
    }
    
    private LocalDate incrementDateByTimeUnit(LocalDate date, String timeUnit) {
        return switch (timeUnit) {
            case "week" -> date.plusWeeks(1);
            case "month" -> date.plusMonths(1);
            default -> date.plusDays(1);
        };
    }

    @Override
    public Map<String, Object> getEncyclopediaCategoryDistribution() {
        Map<String, Object> result = new HashMap<>();
        
        // 按科属统计
        List<Map<String, Object>> familyDistribution = baseMapper.getFamilyDistribution();
        result.put("family", familyDistribution);
        
        // 按属统计
        List<Map<String, Object>> genusDistribution = baseMapper.getGenusDistribution();
        result.put("genus", genusDistribution);
        
        // 按难度统计
        List<Map<String, Object>> difficultyDistribution = baseMapper.getDifficultyDistribution();
        result.put("difficulty", difficultyDistribution);
        
        return result;
    }
}